package com.hulei.studyproject.druid.aop;

import com.hulei.studyproject.druid.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 指定数据源注解切面(Master,Slave)
 */
@Slf4j
@Aspect
@Component
@Order(1)
public class DataSourceSwitchAOP {

    /**
     * 主库注解@Master
     */
    @Before("@annotation(com.hulei.studyproject.druid.annotation.Master) && !@annotation(com.hulei.studyproject.druid.annotation.Slave)")
    public void setWriteDataSourceType() {
        DynamicDataSourceContextHolder.setMaster();
    }

    /**
     * 从库注解@Slave(从alpha、beta库中随机取一个，也可分别定义注解)
     */
    @Before("@annotation(com.hulei.studyproject.druid.annotation.Slave) && !@annotation(com.hulei.studyproject.druid.annotation.Master)")
    public void setReadDataSourceType() {
        DynamicDataSourceContextHolder.setSlave();
    }

    /**
     * 方法执行完毕后
     */
    @After("(@annotation(com.hulei.studyproject.druid.annotation.Slave) && !@annotation(com.hulei.studyproject.druid.annotation.Master)) || (@annotation(com.hulei.studyproject.druid.annotation.Master) && !@annotation(com.hulei.studyproject.druid.annotation.Slave))")
    public void clearDataSourceType() {
        DynamicDataSourceContextHolder.clearDataSourceType();
    }

}

